<?php
class PortalWebServiceDataPackage extends PortalWebServiceDataBase{

	protected $db_handle;
	protected $lang_id=array(
		1=>'zh-hant-hk',
		2=>'en-hk',
		3=>'zh-hans-hk',
	);
	protected $status=array(
		'Inactive','Published','Unpublished'
	);

	static $country_list = array();

	public function __construct($config, $timeless, $time_now) {
		parent::__construct($config, $timeless, $time_now);
		$this->createReadableRecordFactory();
	}
	private function createReadableRecordFactory() {
		$readers = array ();
		foreach ($this->server_config->package_db->readers->reader as $reader) {
			$readers[] = array(
				'host' => (string) $reader->dbhost,
				'user' => (string) $reader->dbuser,
				'pass' => (string) $reader->dbpass,
				'name' => (string) $reader->dbname
			);
		}
		$db = $readers[array_rand($readers)];
		$this->db_handle = new ReadableRecordFactory($db['host'], $db['user'], $db['pass'], $db['name']);
	} 

	protected function __check_lang($lang){
		$lang    = strtolower(trim($lang));
		$lang_id = array_search($lang,$this->lang_id);
		if($lang_id === false){
			throw new PortalWebServiceException('lang',PortalWebServiceException::PARAMETERS_ERROR);
		}
		return $lang_id;
	}
	protected function __check_country_code($country_code){
		if(empty(self::$country_list)) {
			$all_country = ParseCountryCode::parseXml((string)$this->server_config->country_file);
			foreach($all_country as $zone){
				foreach($zone as $row){
					foreach($row as $code=>$label){
						self::$country_list[$code] = $label;
					}
				}
			}
		}
		$country_code = explode(',',strtoupper(trim($country_code,' ,')));
		$new_country_code = array();
		foreach($country_code as $code){
			if(trim($code)){
				if(!array_key_exists($code,self::$country_list)){
					throw new PortalWebServiceException('country_code',PortalWebServiceException::PARAMETERS_ERROR);
				}
				$new_country_code[] = $code;
			}
		}
		return $new_country_code;

		#$country_code = strtoupper(trim($country_code,' ,'));
		#if(!preg_match('/^([A-Z0-9]{2},?)+$/',$country_code.',')){
		#	throw new PortalWebServiceException('country_code',PortalWebServiceException::PARAMETERS_ERROR);
		#}
		#return explode(',',$country_code);
	}

	public function _list($lang='en-hk',$format='json'){
		$status = (int)$this->server_config->package_db->active_status_code;
		$lang   = $this->__check_lang($lang);
		$format = $this->__check_format($format);
		$data = array(
			'total' => 0,
			'size'  => 0,
			'lang'  => $this->lang_id[$lang],
			'data'  => array()
		);

        if ($this->timeless === TRUE) {
            $sql = "
                select *,
                UNIX_TIMESTAMP(publish_datetime) as publish_datetime,
                UNIX_TIMESTAMP(expire_datetime) as expire_datetime,
                UNIX_TIMESTAMP(created_at) as created_at,
                UNIX_TIMESTAMP(modified_at) as modified_at
                from package where (status=$status) order by pkg_order 
                ";
        } else {
            $current = date('Y-m-d H:i:s', $this->time_now);
            $sql = "
                select *,
                UNIX_TIMESTAMP(publish_datetime) as publish_datetime,
                UNIX_TIMESTAMP(expire_datetime) as expire_datetime,
                UNIX_TIMESTAMP(created_at) as created_at,
                UNIX_TIMESTAMP(modified_at) as modified_at
                from package where (publish_datetime <= '{$current}' and expire_datetime >= '{$current}') and (status=$status) order by pkg_order 
                ";
        }

		$rs = $this->db_handle->findBySql('Package',$sql);
		if($rs){
			$total = count($rs);
			$data['total'] = $total;
			$data['size']  = $total;
			foreach($rs as $index => $row){
				$row->clubs       = $row->clubs ? json_decode($row->clubs) : array();
				$package_lang     = $this->db_handle->findInstance('PackageLanguage',array($row->version_id,$row->package_id,$lang));
				$row->title       = $package_lang->title;
				$row->description = $package_lang->description;
				$row->status      = $this->status[$row->status];
				$data['data'][] = $row;
			}
		}
		return ($format=='xml' ? CommonUtils::arrayToXml($data) : $data);
	}

	public function _packageinfo($pkg_id,$version_id,$lang='en-hk',$format='json',$club_id=0){
		$pkg_id = (int)$this->__check_int($pkg_id,'package_id');
		$ver_id = (int)$this->__check_int($version_id,'version_id');
		$lang   = $this->__check_lang($lang);
		$format = $this->__check_format($format);
		$sql = "
			select *,
			UNIX_TIMESTAMP(publish_datetime) as publish_datetime,
			UNIX_TIMESTAMP(expire_datetime) as expire_datetime,
			UNIX_TIMESTAMP(created_at) as created_at,
			UNIX_TIMESTAMP(modified_at) as modified_at
			from package where version_id=$ver_id and package_id=$pkg_id
		";
		$rs = $this->db_handle->findBySql('Package',$sql);
		if(empty($rs[0])) return null;

		$package      = $rs[0];
		$package_lang = $this->db_handle->findInstance('PackageLanguage',array($ver_id,$pkg_id,$lang));
		if(empty($package) || empty($package_lang)) return null;

		$package->status      = $this->status[$package->status];
		$package->title       = $package_lang->title;
		$package->description = $package_lang->description;
		$package->clubs       = $package->clubs ? json_decode($package->clubs) : array();
		if($club_id){
			$package->clubs = isset($package->clubs[$club_id]) ? $package->clubs[$club_id] : '';
		}
		return ($format=='xml' ? CommonUtils::arrayToXml($package) : $package);
	}

	public function _listbyshopid($shop_ids='',$lang='en-hk',$format='json'){
		$status = (int)$this->server_config->package_db->active_status_code;
		$lang   = $this->__check_lang($lang);
		$format = $this->__check_format($format);

        if ($this->timeless === TRUE) {
            $sql = "
                select *,
                UNIX_TIMESTAMP(publish_datetime) as publish_datetime,
                UNIX_TIMESTAMP(expire_datetime) as expire_datetime,
                UNIX_TIMESTAMP(created_at) as created_at,
                UNIX_TIMESTAMP(modified_at) as modified_at
                from package where (status=$status) order by pkg_order 
                ";
        } else {
            $current = date('Y-m-d H:i:s');
            //$current = date('Y-m-d H:i:s', $this->time_now);
            $sql = "
                select *,
                UNIX_TIMESTAMP(publish_datetime) as publish_datetime,
                UNIX_TIMESTAMP(expire_datetime) as expire_datetime,
                UNIX_TIMESTAMP(created_at) as created_at,
                UNIX_TIMESTAMP(modified_at) as modified_at
                from package where (publish_datetime <= '{$current}' and expire_datetime >= '{$current}') and (status=$status) order by pkg_order 
                ";
        }
		$rs = $this->db_handle->findBySql('Package',$sql);

		$shops = array();
		foreach($rs as $row){
			$row->clubs = $row->clubs ? json_decode($row->clubs) : array();

			if(!isset($row->title)){
				$package_lang     = $this->db_handle->findInstance('PackageLanguage',array($row->version_id,$row->package_id,$lang));
				$row->title       = $package_lang->title;
				$row->description = $package_lang->description;
				$row->status = $this->status[$row->status];
			}

			if($shop_ids){
				$all_shop = explode(',',$shop_ids);
				foreach($all_shop as $shop){
					$shop_str = trim($row->shops);
					if($shop_str && FALSE !== strpos(",$shop_str,",",$shop,")){
						$shops[$shop][] = (array)$row;
					}
				}
			}else{
				$all_shop = explode(',',$row->shops);
				foreach($all_shop as $shop){
					$shops[$shop][] = (array)$row;
				}
			}
		}
		return ($format=='xml' ? CommonUtils::arrayToXml($shops) : $shops);
	}

	public function _listbycountrycode($country_code='',$lang='en-hk',$format='json',$shop_ids=''){
		$status = (int)$this->server_config->package_db->active_status_code;
		$code   = ($country_code ? $this->__check_country_code($country_code) : array());
		$lang   = $this->__check_lang($lang);
		$format = $this->__check_format($format);

		$countries = array();
		$packages  = array();
        if ($this->timeless === TRUE) {
            $sql = "
                select *,
                UNIX_TIMESTAMP(publish_datetime) as publish_datetime,
                UNIX_TIMESTAMP(expire_datetime) as expire_datetime,
                UNIX_TIMESTAMP(created_at) as created_at,
                UNIX_TIMESTAMP(modified_at) as modified_at
                from package where (status=$status) order by pkg_order
                ";
        } else {
            //$current = date('Y-m-d H:i:s', $this->time_now);
            $current = date('Y-m-d H:i:s');
            $sql = "
                select *,
                UNIX_TIMESTAMP(publish_datetime) as publish_datetime,
                UNIX_TIMESTAMP(expire_datetime) as expire_datetime,
                UNIX_TIMESTAMP(created_at) as created_at,
                UNIX_TIMESTAMP(modified_at) as modified_at
                from package where (publish_datetime <= '{$current}' and expire_datetime >= '{$current}') and (status=$status) order by pkg_order
                ";
        }
		$all_package = $this->db_handle->findBySql('Package',$sql);
		#$all_country = $this->db_handle->findAll('Country');
		#foreach($all_country as $row){
		#	$countries[$row->code] = $row->system_label;
		#}
		if($code){
			$tmp = array();
			foreach($code as $c){
				$tmp[$c] = self::$country_list[$c];
			}
			  $countries = $tmp;
		}else $countries = self::$country_list;

		$all_shop = $shop_ids ? explode(',',$shop_ids) : array();

		foreach($all_package as $row){
			$allow = strtoupper($row->country_allow_list);
			$deny  = strtoupper($row->country_deny_list) ;
			$row->clubs = $row->clubs ? json_decode($row->clubs) : array();
			
			# check shop ids
			if($all_shop){
				$skip = true;
				foreach($all_shop as $shop){
					$shop_str = trim($row->shops);
					if($shop_str && FALSE !== strpos(",$shop_str,",",$shop,")){
						$skip = false;
					}
				}
				if($skip) continue;
			}

			foreach($countries as $country=>$country_name){
				$row->country_name = $country_name;
				if(('ALL'==$allow && FALSE===strpos($deny,$country)) || ('ALL'==$deny && FALSE!==strpos($allow,$country))){
					if(!isset($row->title)){
						$package_lang     = $this->db_handle->findInstance('PackageLanguage',array($row->version_id,$row->package_id,$lang));
						$row->title       = $package_lang->title;
						$row->description = $package_lang->description;
						$row->status = $this->status[$row->status];
					}
					$data = (array)$row;
					array_shift($data);
					$packages[$country][] = $data;
					continue;
				}
			}
		}

		return ($format=='xml' ? CommonUtils::arrayToXml($packages) : $packages);
	}
}
